package protobuf

import (
	"github.com/golang/protobuf/proto"
	"reflect"
	"strings"
)

var (
	messages = make(map[string]reflect.Type)
)

func Register(msgType reflect.Type) {
	if msgType.Kind() == reflect.Ptr {
		msgType = msgType.Elem()
	}

	if msgType.Kind() != reflect.Struct {
		return
	}

	item := reflect.New(msgType)
	if _, ok := item.Interface().(proto.Message); !ok {
		return
	}

	name := getName(msgType)
	if _, exists := messages[name]; exists {
		return
	}

	messages[name] = msgType
}

func New(name string) (result proto.Message, exists bool) {
	var msgType reflect.Type
	if msgType, exists = messages[name]; exists {
		msgValue := reflect.New(msgType)
		result = msgValue.Interface().(proto.Message)
	}

	return
}

func Name(msg proto.Message) string {
	msgType := reflect.TypeOf(msg)
	return getName(msgType)
}

func getName(msgType reflect.Type) string {
	name := msgType.String()
	if strings.HasPrefix(name, "*") {
		name = name[1:]
	}

	return name
}
